from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import F
from django.views import View
import logging
from .models import Tag,News,Banner
from . import paginator_num
from utils.return_json import json_response
from user.models import User

# Create your views here.
logger=logging.getLogger('django')
def index(request):
    tags=Tag.objects.only('id','name').filter(is_delete=False)
    return render(request,"news/index.html" ,context={"tags":tags})


class NewsListView(View):
    def get(self,request):
        """
       点击文章分类，获取分类id
        """
        try:
            tag_id = int(request.GET.get('tag',0))
        except Exception as f:
            logger.error('标签错误,\n{}'.format(f))
            tag_id=0
        """
        点击加载更多，获取加载的页面id
        """
        try:
            page=request.GET.get('page',0)
        except Exception as f:
            logger.error('页码错误,\n{}'.format(f))
            page=1
        """
        清洗news页面显示出来的数据
        """
        news_queryset = News.objects.values('id', 'title', 'digest', 'image_url', 'update_time').annotate(
            tag_name=F('tag__name'), author=F('author__username')
        )

        """
        过滤筛选出来的数据
        """
        news = news_queryset.filter(is_delete=False,tag_id=tag_id) or news_queryset.filter(is_delete=False)

        """
        分页
        """
        paginator=Paginator(news,paginator_num.PAGINATOR_NUM)#传入筛选出来的数据，页面显示数目
        #第一个参数传入一个可迭代的对象，第二个参数传入每页显示的个数

        """
        页面容错处理，解决用户恶意输入页面id
        """
        news_info = paginator.get_page(page)#get_page方法分页器自带有的，获取当前页的数据

        """
        返回json数据
        """
        data = {
            'total_pages' : paginator.num_pages,#num_pages分页器自带有，返回总页数
            'news': list(news_info)
        }
        return json_response(data=data)#Django json数据不支持处理时间类型，需要自定义的json编码器以便能够序列化datetime数据类型

class BannerView(View):
    def get(self,request):
        Banner.objects.values('image_url',)